import {
  ActionType,
  ProColumns,
  FooterToolbar,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Divider, Input, InputNumber, message, Popconfirm } from 'antd';
import { useRef, useState } from 'react';
import CreateForm from '@/components/CreateForm';
import services from '@/services/receivingOrderInfo';
import React from 'react';


const { queryList, addData, modifyData, deleteData } = services.ReceivingOrderInfoController

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (id: number | string | null = null, fields: API.ReceivingOrderInfo, receivingOrderId: number | undefined) => {
  const hide = message.loading('正在操作');
  try {
    console.log(fields)
    id ? await modifyData({ id }, { ...fields, receivingOrderId }) : await addData({ ...fields, receivingOrderId });
    hide();
    message.success('操作成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (id:number|undefined) => {
  const hide = message.loading('正在删除');
  if (!id) return true;
  try {
    await deleteData({
      id
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const ApprovesWin = ({ id }: any) => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [winProps, setWindowProps] = useState<any>({ title: '新建', id: null, record: {}, width: 1200 })
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<API.ReceivingOrderInfo[]>([]);
  const columns: ProColumns<API.ReceivingOrderInfo>[] = [
    {
      title: '处理环节', dataIndex: 'processStep', width: 200, ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '处理人', dataIndex: 'processor', width: 200, ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '处理时间', dataIndex: 'processTime', valueType: 'date', width: 200, ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '处理意见', dataIndex: 'processComments', width: 200, ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 100,
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              setWindowProps({ ...winProps, title: '编辑', id: record.id, record, width: 420 })
              handleModalVisible(true)
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <Popconfirm
            title="温馨提示"
            description="确定删除该条数据？"
            okText="确定"
            cancelText="取消"
            onConfirm={async () => {
              await handleRemove(record.id);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            <a color='red'>删除</a>
          </Popconfirm>
        </>
      ),
    },
  ];

  return (
    <>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        search={false}
        scroll={{ x: 'max-content' }}
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
            onClick={() => {
              setWindowProps({ ...winProps, title: '新建', id: null, record: {}, width: 420 })
              handleModalVisible(true)
            }}
          >
            新建
          </Button>,
        ]}
        request={async (params) => {
          const { data, success,total } = await queryList({
            ...params,
            receivingOrderId: id
          });
          return {
            data: data || [],
            success,
            total
          };
        }}
        columns={columns}
        rowSelection={{
          type: 'radio',
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />
      <CreateForm
        onCancel={() => {
          handleModalVisible(false)
        }}
        modalVisible={createModalVisible}
        {...winProps}
      >
        <ProTable<API.ReceivingOrderInfo, API.ReceivingOrderInfo>
          onSubmit={async (value) => {
            const success = await handleAdd(winProps.id, value, id);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}

          rowKey="id"
          type="form"
          form={{
            initialValues: winProps.record,
            labelAlign: 'left',
          }}
          columns={columns}
        />
      </CreateForm>
    </>
  );
}

export default ApprovesWin;